<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTag\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTag\Contract\RoomTagContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagGroupContract;

/**
 * 客户群标签-列表.
 *
 * Class Index
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomTagGroupContract
     */
    protected $roomTagGroupService;

    /**
     * @Inject
     * @var RoomTagContract
     */
    protected $roomTagService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/roomTag/index", methods="get")
     */
    public function handle()
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        $count = 0;
        $list = $this->roomTagGroupService->getRoomTagGroupsByCorpId([user()['corpIds'][0]], ['id', 'group_name']);
        foreach ($list as $k => $v) {
            $list[$k]['tags'] = $this->roomTagService->getRoomTagsByGroupIds([$v['id']], ['id', 'name']);
            $count += count($list[$k]['tags']);
        }
        return ['count' => $count, 'list' => $list];
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
        ];
    }
}
